package com.example.kill.service.impl;

import com.example.kill.dao.KillOrderInfoMapper;
import com.example.kill.dao.KillOrderMapper;
import com.example.kill.pojo.KillOrder;
import com.example.kill.pojo.KillOrderInfo;
import com.example.kill.pojo.KillUser;
import com.example.kill.redis.OrderKey;
import com.example.kill.redis.RedisService;
import com.example.kill.service.OrderService;
import com.example.kill.vo.GoodsVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class OrderServiceImpl implements OrderService {

    private static Logger LOGGER = LoggerFactory.getLogger(OrderServiceImpl.class);
    @Resource
    KillOrderMapper killOrderMapper;

    @Resource
    KillOrderInfoMapper orderInfoMapper;

    @Autowired
    private RedisService redisService;

    @Transactional
    public KillOrderInfo createOrder(KillUser killUser, GoodsVo goodsVo) {
        // 2 下订单 3 写入秒杀订单
        KillOrderInfo orderInfo = new KillOrderInfo();
        orderInfo.setCreateDate(new Date());
        orderInfo.setDeliveryAddrId(0L);
        orderInfo.setGoodsCount(1);
        orderInfo.setGoodsId(goodsVo.getId());
        orderInfo.setGoodsName(goodsVo.getGoodsName());
        orderInfo.setGoodsPrice(goodsVo.getKillPrice());
        orderInfo.setOrderChannel(1);
        orderInfo.setStatus(0);
        orderInfo.setUserId(killUser.getId());
        //保存返回的订单ID
        long orderId = orderInfoMapper.save(orderInfo);

        LOGGER.info("orderId={}",orderInfo.getId());

        KillOrder killOrder = new KillOrder();
        killOrder.setGoodsId(goodsVo.getId());
        killOrder.setOrderId(orderInfo.getId());
        killOrder.setUserId(killUser.getId());
        killOrderMapper.insertSelective(killOrder);
        //把秒杀订单存入缓存
        redisService.set(OrderKey.getKillOrderByUidGid,""+killUser.getId()+"_"+goodsVo.getId(),killOrder);
        return orderInfo;
    }

    @Override
    public KillOrderInfo getOrderById(long orderId) {
        return orderInfoMapper.selectByPrimaryKey(orderId);
    }


}
